/*
 * Copyright (c) Thorben Linneweber and others
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Jitter2.LinearMath;
using Jitter2.UnmanagedMemory;

using SoftFloat;

namespace Jitter2.Dynamics.Constraints
{
	
	/// <summary>
	/// Constrains two bodies to only allow rotation around a specified axis, removing two angular degrees of freedom, or three if a limit is enforced.
	/// </summary>
	public unsafe class HingeAngle : Constraint
	{
	    [StructLayout(LayoutKind.Sequential)]
	    public struct HingeAngleData
	    {
	        internal int _internal;
	        public delegate*<ref ConstraintData, void> Iterate;
	        public delegate*<ref ConstraintData, sfloat, void> PrepareForIteration;
	
	        public JHandle<RigidBodyData> Body1;
	        public JHandle<RigidBodyData> Body2;
	
	        public sfloat MinAngle;
	        public sfloat MaxAngle;
	
	        public sfloat BiasFactor;
	        public sfloat LimitBias;
	
	        public sfloat LimitSoftness;
	        public sfloat Softness;
	
	        public NVector3 Axis;
	        public NQuaternion Q0;
	
	        public NVector3 AccumulatedImpulse;
	        public NVector3 Bias;
	
	        public JMatrix EffectiveMass;
	        public JMatrix Jacobian;
	
	        public ushort Clamp;
	    }
	
	    private JHandle<HingeAngleData> handle;
	
	    protected override void Create()
	    {
	        Trace.Assert(sizeof(HingeAngleData) <= sizeof(ConstraintData));
	        iterate = &Iterate;
	        prepareForIteration = &PrepareForIteration;
	        handle = JHandle<ConstraintData>.AsHandle<HingeAngleData>(Handle);
	    }
	
	    /// <summary>
	    /// Initializes the constraint.
	    /// </summary>
	    /// <param name="axis">Axis in world space for which relative angular movement is allowed.</param>
	    public void Initialize(NVector3 axis, AngularLimit limit)
	    {
	        ref HingeAngleData data = ref handle.Data;
	        ref RigidBodyData body1 = ref data.Body1.Data;
	        ref RigidBodyData body2 = ref data.Body2.Data;
	
	        data.Softness = (sfloat)0.001f;
	        data.LimitSoftness = (sfloat)0.001f;
	        data.BiasFactor = (sfloat)0.2f;
	        data.LimitBias = (sfloat)0.1f;
	
	        data.MinAngle = libm.Sin((sfloat)limit.From / (sfloat)2.0f);
	        data.MaxAngle = libm.Sin((sfloat)limit.To / (sfloat)2.0f);
	
	        data.Axis = NVector3.TransposedTransform(axis, body2.Orientation);
	
	        NQuaternion q1 = body1.Orientation;
	        NQuaternion q2 = body2.Orientation;
	
	        data.Q0 = q2.Conjugate() * q1;
	    }
	
	    public AngularLimit Limit
	    {
	        set
	        {
	            ref HingeAngleData data = ref handle.Data;
	            data.MinAngle = libm.Sin((sfloat)value.From / (sfloat)2.0f);
	            data.MaxAngle = libm.Sin((sfloat)value.To / (sfloat)2.0f);
	        }
	    }
	
	    public static void PrepareForIteration(ref ConstraintData constraint, sfloat idt)
	    {
	        ref HingeAngleData data = ref Unsafe.AsRef<HingeAngleData>(Unsafe.AsPointer(ref constraint));
	
	        ref RigidBodyData body1 = ref data.Body1.Data;
	        ref RigidBodyData body2 = ref data.Body2.Data;
	
	        NQuaternion q1 = body1.Orientation;
	        NQuaternion q2 = body2.Orientation;
	
	        NVector3 p0 = MathHelper.CreateOrthonormal(data.Axis);
	        NVector3 p1 = data.Axis % p0;
	
	        NQuaternion quat0 = data.Q0 * q1.Conjugate() * q2;
	
	        NVector3 error;
	        error.X = NVector3.Dot(p0, new NVector3(quat0.X, quat0.Y, quat0.Z));
	        error.Y = NVector3.Dot(p1, new NVector3(quat0.X, quat0.Y, quat0.Z));
	        error.Z = NVector3.Dot(data.Axis, new NVector3(quat0.X, quat0.Y, quat0.Z));
	
	        data.Clamp = 0;
	
	        JMatrix m0 = (-(sfloat)1.0f / (sfloat)2.0f) * QMatrix.ProjectMultiplyLeftRight(data.Q0 * q1.Conjugate(), q2);
	
	        if (quat0.W < (sfloat)0.0f)
	        {
	            error *= -(sfloat)1.0f;
	            m0 *= -(sfloat)1.0f;
	        }
	
	        data.Jacobian.UnsafeGet(0) = NVector3.TransposedTransform(p0, m0);
	        data.Jacobian.UnsafeGet(1) = NVector3.TransposedTransform(p1, m0);
	        data.Jacobian.UnsafeGet(2) = NVector3.TransposedTransform(data.Axis, m0);
	
	        data.EffectiveMass = JMatrix.TransposedMultiply(data.Jacobian, JMatrix.Multiply(body1.InverseInertiaWorld + body2.InverseInertiaWorld, data.Jacobian));
	
	        data.EffectiveMass.M11 += data.Softness * idt;
	        data.EffectiveMass.M22 += data.Softness * idt;
	        data.EffectiveMass.M33 += data.LimitSoftness * idt;
	
	        sfloat maxa = data.MaxAngle;
	        sfloat mina = data.MinAngle;
	
	        if (error.Z > maxa)
	        {
	            data.Clamp = 1;
	            error.Z -= maxa;
	        }
	        else if (error.Z < mina)
	        {
	            data.Clamp = 2;
	            error.Z -= mina;
	        }
	        else
	        {
	            data.AccumulatedImpulse.Z = 0;
	            data.EffectiveMass.M33 = 1;
	            data.EffectiveMass.M31 = data.EffectiveMass.M13 = 0;
	            data.EffectiveMass.M32 = data.EffectiveMass.M23 = 0;
	
	            // TODO: do he have to set them to zero here, explicitly?
	            //       does this also has to be done in PointOnLine?
	            data.Jacobian.M13 = data.Jacobian.M23 = data.Jacobian.M33 = 0;
	        }
	
	        JMatrix.Inverse(data.EffectiveMass, out data.EffectiveMass);
	
	        data.Bias = error * idt;
	        data.Bias.X *= data.BiasFactor;
	        data.Bias.Y *= data.BiasFactor;
	        data.Bias.Z *= data.LimitBias;
	
	        body1.AngularVelocity += NVector3.Transform(NVector3.Transform(data.AccumulatedImpulse, data.Jacobian), body1.InverseInertiaWorld);
	        body2.AngularVelocity -= NVector3.Transform(NVector3.Transform(data.AccumulatedImpulse, data.Jacobian), body2.InverseInertiaWorld);
	    }
	
	    public JAngle Angle
	    {
	        get
	        {
	            ref HingeAngleData data = ref handle.Data;
	            NQuaternion q1 = data.Body1.Data.Orientation;
	            NQuaternion q2 = data.Body2.Data.Orientation;
	
	            NQuaternion quat0 = data.Q0 * q1.Conjugate() * q2;
	
	            if (quat0.W < (sfloat)0.0f)
	            {
	                quat0 *= -(sfloat)1.0f;
	            }
	
	            sfloat error = NVector3.Dot(data.Axis, new NVector3(quat0.X, quat0.Y, quat0.Z));
	            return (JAngle)((sfloat)2.0f * libm.Asin(error));
	        }
	    }
	
	    public sfloat Softness
	    {
	        get => handle.Data.Softness;
	        set => handle.Data.Softness = value;
	    }
	
	    public sfloat LimitSoftness
	    {
	        get => handle.Data.LimitSoftness;
	        set => handle.Data.LimitSoftness = value;
	    }
	
	    public sfloat Bias
	    {
	        get => handle.Data.BiasFactor;
	        set => handle.Data.BiasFactor = value;
	    }
	
	    public sfloat LimitBias
	    {
	        get => handle.Data.LimitBias;
	        set => handle.Data.LimitBias = value;
	    }
	
	    public NVector3 Impulse => handle.Data.AccumulatedImpulse;
	
	    public static void Iterate(ref ConstraintData constraint, sfloat idt)
	    {
	        ref HingeAngleData data = ref Unsafe.AsRef<HingeAngleData>(Unsafe.AsPointer(ref constraint));
	        ref RigidBodyData body1 = ref constraint.Body1.Data;
	        ref RigidBodyData body2 = ref constraint.Body2.Data;
	
	        NVector3 jv = NVector3.TransposedTransform(body1.AngularVelocity - body2.AngularVelocity, data.Jacobian);
	
	        NVector3 softness = data.AccumulatedImpulse * idt;
	        softness.X *= data.Softness;
	        softness.Y *= data.Softness;
	        softness.Z *= data.LimitSoftness;
	
	        NVector3 lambda = -(sfloat)1.0f * NVector3.Transform(jv + data.Bias + softness, data.EffectiveMass);
	
	        NVector3 origAcc = data.AccumulatedImpulse;
	
	        data.AccumulatedImpulse += lambda;
	
	        if (data.Clamp == 1)
	        {
	            data.AccumulatedImpulse.Z = libm.Min(0, data.AccumulatedImpulse.Z);
	        }
	        else if (data.Clamp == 2)
	        {
	            data.AccumulatedImpulse.Z = libm.Max(0, data.AccumulatedImpulse.Z);
	        }
	        else
	        {
	            origAcc.Z = 0;
	            data.AccumulatedImpulse.Z = 0;
	        }
	
	        lambda = data.AccumulatedImpulse - origAcc;
	
	        body1.AngularVelocity += NVector3.Transform(NVector3.Transform(lambda, data.Jacobian), body1.InverseInertiaWorld);
	        body2.AngularVelocity -= NVector3.Transform(NVector3.Transform(lambda, data.Jacobian), body2.InverseInertiaWorld);
	    }
	}
}
